using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Globalization;
using System.IO;
using AutoMapper;
using Microsoft.Extensions.Logging;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.Models.Pagination;
using Terra.Core.Common.ErrorCodes.Constants;
using Terra.Data.Repository.Logging;
using Terra.Data.UnitOfWork;
using Terra.Service.Common.Base;
using Terra.Data.Models.Loggings;
using Terra.Service.Logging.Interfaces;

namespace Terra.Service.Logging.Implementations;

/// <summary>
/// 异常日志服务实现
/// </summary>
public class ExceptionLogService : AppServiceBase, IExceptionLogService
{
    private readonly IExceptionLogRepository _exceptionLogRepository;
    private readonly ILogger<ExceptionLogService> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    public ExceptionLogService(
        IUnitOfWork unitOfWork,
        IMapper mapper,
        IExceptionLogRepository exceptionLogRepository,
        ILogger<ExceptionLogService> logger) : base(unitOfWork, mapper)
    {
        _exceptionLogRepository = exceptionLogRepository;
        _logger = logger;
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<PagedList<ExceptionItemDto>>> GetPagedListAsync(ExceptionQueryDto query)
    {
        try
        {
            var result = await _exceptionLogRepository.GetPagedListAsync(query);
            var items = Mapper.Map<List<ExceptionItemDto>>(result.Items);
            var pagedList = new PagedList<ExceptionItemDto>(items, result.TotalCount, query.PageIndex, query.PageSize);

            return ApiResponse<PagedList<ExceptionItemDto>>.Success(pagedList);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取异常日志列表失败");
            return ApiResponse<PagedList<ExceptionItemDto>>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<ExceptionDetailDto>> GetByIdAsync(Guid id)
    {
        try
        {
            var entity = await _exceptionLogRepository.GetByIdAsync(id);
            if (entity == null)
            {
                return ApiResponse<ExceptionDetailDto>.Error(SystemErrorCodes.NotFound);
            }

            var dto = Mapper.Map<ExceptionDetailDto>(entity);
            return ApiResponse<ExceptionDetailDto>.Success(dto);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取异常日志详情失败, ID: {Id}", id);
            return ApiResponse<ExceptionDetailDto>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<List<ExceptionStatsDto>>> GetExceptionStatsAsync(DateTime? startTime, DateTime? endTime)
    {
        try
        {
            var stats = await _exceptionLogRepository.GetExceptionStatsAsync(startTime, endTime);
            return ApiResponse<List<ExceptionStatsDto>>.Success(stats);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取异常统计信息失败");
            return ApiResponse<List<ExceptionStatsDto>>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<List<ExceptionStatsFrontendDto>>> GetFrontendStatsAsync(DateTime? startTime, DateTime? endTime)
    {
        try
        {
            var stats = await _exceptionLogRepository.GetFrontendStatsAsync(startTime, endTime);
            return ApiResponse<List<ExceptionStatsFrontendDto>>.Success(stats);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取前端异常统计信息失败");
            return ApiResponse<List<ExceptionStatsFrontendDto>>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<int>> CleanAsync(DateTime beforeTime)
    {
        try
        {
            var count = await _exceptionLogRepository.CleanAsync(beforeTime);
            await UnitOfWork.SaveChangesAsync();
            return ApiResponse<int>.Success(count, $"成功清理 {count} 条异常日志");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理异常日志失败");
            return ApiResponse<int>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public async Task<ApiResponse<int>> BatchDeleteAsync(IEnumerable<Guid> ids)
    {
        try
        {
            var count = await _exceptionLogRepository.BatchDeleteAsync(ids);
            await UnitOfWork.SaveChangesAsync();
            return ApiResponse<int>.Success(count, $"成功删除 {count} 条异常日志");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量删除异常日志失败");
            return ApiResponse<int>.Error(SystemErrorCodes.SystemError);
        }
    }

    /// <inheritdoc/>
    public  Task<ApiResponse<byte[]>> ExportAsync(ExceptionQueryDto query)
    {
        throw new NotImplementedException();
        //try
        //{

        //    var logs = await _exceptionLogRepository.ExportAsync(query);
        //    var dtos = Mapper.Map<List<ExceptionDetailDto>>(logs);

        //    using var memoryStream = new MemoryStream();
        //    using var writer = new StreamWriter(memoryStream, Encoding.UTF8);
        //    using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);

        //    await csv.WriteRecordsAsync(dtos);
        //    await writer.FlushAsync();

        //    return ApiResponse<byte[]>.Success(memoryStream.ToArray());
        //}
        //catch (Exception ex)
        //{
        //    _logger.LogError(ex, "导出异常日志失败");
        //    return ApiResponse<byte[]>.Error(SystemErrorCodes.SystemError);
        //}
    }
}